package socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import dao.CommonDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.Log;

/**
 * @author Administrator
 *
 * 转发消息方式，服务器
 * 
 *         设备消息处理类
 *
 * 心跳包
 * {id:"123",status:1,type:"heart"}
 *  
 *
 */
@Repository
public class ServerForward {
	@Resource
	private CommonDao commonDao;

	public static Map<String, String> map = new HashMap<String, String>();

	DatagramSocket ds;
	
	public void init(){
		if(ds!=null){
			ds.disconnect();
			ds.close();
		}
		try {
			byte by[] = new byte[2000];
			DatagramPacket dp = new DatagramPacket(by, 0, by.length);
			ds = new DatagramSocket(1234);
			while (true) {
				System.out.println("wait for client...");
				ds.receive(dp);// 等待接收客户端消息，阻塞函数，一个dp就是一个客户端的一条消息
				System.out.println("recive a message!");
				new Thread(new Parse(ds, dp)).start();
				dp.setData(by, 0, by.length);
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				Thread.sleep(5000);
				init();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}

	public void start() {
		Log.outLog("parse message thread start success!");
		try {
			
			new Thread(new Runnable() {
				@Override
				public void run() {
					new SendCommand().start();
				}
			}).start();
			
			init();
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class Parse implements Runnable {
		DatagramPacket dp = null;
		DatagramSocket ds = null;

		public Parse(DatagramSocket ds, DatagramPacket dp) {
			this.dp = dp;
			this.ds = ds;
		}

		@Override
		public void run() {
			try {
				System.out.println("success");
				String message = new String(dp.getData(), 0, dp.getLength());// 客户端消息
				System.out.println("message:" + message);
				SocketAddress socketAddress = dp.getSocketAddress();
				InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
				int clientPort = inetSocketAddress.getPort();
				String ip = inetSocketAddress.getAddress().getHostAddress();
				JSONObject messageJson = JSONObject.fromObject(message);
				String type = messageJson.getString("type");// 包类型
				if (type.equals("heart")) {
					messageJson.put("type", "heartReturn");
					byte buf[] = messageJson.toString().getBytes();
					dp.setData(buf, 0, buf.length);
					ds.send(dp);

					String id = messageJson.getString("id");// 设备id
					int status = messageJson.getInt("status");
					String sql = "SELECT id FROM sheBei WHERE id='" + id + "'";
					JSONArray data = commonDao.list(sql);
					if (data.size() > 0) {
						sql = "update sheBei set ip='" + ip + "',port='" + clientPort + "',status=" + status
								+ " where id='" + id + "'";
						commonDao.execute(sql);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 发送command类
	 */
	public class SendCommand {
		int executeTime = 1000;// 遍历command表一次之后，等待多长时间再次遍历

		public void start() {
			try {
				String sql = "SELECT a.*,sheBei.ip,sheBei.port FROM (SELECT * FROM command) a "
						+ "LEFT JOIN sheBei ON a.sheBeiId=sheBei.id AND sheBei.status=1";
				JSONArray data = commonDao.list(sql);
				for (int i = 0; i < data.size(); i++) {
					JSONObject obj = data.getJSONObject(i);
					new Thread(new SendCommandThread(ds, obj)).start();
				}
				Thread.sleep(executeTime);
				start();
			} catch (Exception e) {
				start();
				e.printStackTrace();
			}
		}

		class SendCommandThread implements Runnable {
			DatagramSocket ds = null;
			DatagramPacket dp = null;
			String message = "";
			JSONObject jsonData = null;

			public SendCommandThread(DatagramSocket ds, JSONObject jsonData) {
				this.ds = ds;
				this.jsonData = jsonData;
			}

			public void run() {
				try {
					System.out.println(jsonData);
					SocketAddress server = new InetSocketAddress(jsonData.getString("ip"), jsonData.getInt("port"));
					byte buff[] = jsonData.getString("command").getBytes();
					byte buffer[] = new byte[8 * 1024];
					DatagramPacket dp = new DatagramPacket(buff, 0, buff.length, server);
					ds.send(dp);// 发送命令到设备
					System.out.println(jsonData.getString("command") + " : 命令已发送！");
					dp.setData(buffer, 0, 8 * 1024);

					String sql = "delete from command where id='" + jsonData.getString("id") + "'";
					commonDao.execute(sql);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void main(String args[]) throws Exception {
		// Server.start();
	}
}
